package com.atguigu.educenter.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.Result;
import com.atguigu.commonutils.vo.UcenterMemberVO;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.entity.vo.LoginInfoVO;
import com.atguigu.educenter.entity.vo.LoginVO;
import com.atguigu.educenter.entity.vo.RegisterVO;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.servicebase.exception.EduException;
import com.baomidou.mybatisplus.extension.api.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author zr
 * @since 2021-11-22
 */
@RestController
@RequestMapping("/edu/center/member")
//@CrossOrigin
public class UcenterMemberController {
    @Autowired
    private UcenterMemberService ucenterMemberService;

    @ApiOperation("根据时间查询那一天的注册人数")
    @GetMapping("countRegister/{day}")
    public Integer countRegister(@PathVariable String day) {
        Integer count = ucenterMemberService.countRegister(day);
        return count;
    }

    @ApiOperation(value = "会员登录")
    @PostMapping("login")
    public Result loginUser(@RequestBody LoginVO loginVo) {
        // 返回token字符串 用JWT生成
        String token = ucenterMemberService.login(loginVo);
        Map<String, String> map = new HashMap<>();
        map.put("token", token);
        return Result.ok(map).message("登录成功");
    }

    @ApiOperation(value = "会员注册")
    @PostMapping("register")
    public Result register(@RequestBody RegisterVO registerVO) {
        ucenterMemberService.register(registerVO);
        return Result.ok().message("注册成功");
    }

    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("auth/getLoginInfo")
    public Result getLoginInfo(HttpServletRequest request) {
        // 根据request对象 获取头信息 返回用户Id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        LoginInfoVO loginInfoVO = ucenterMemberService.getLoginInfo(memberId);
        Map<String, Object> map = new HashMap<>();
        map.put("item", loginInfoVO);
        return Result.ok(map);
    }

    @ApiOperation(value = "根据用户id查询用户信息")
    @PostMapping("getMemberInfoById/{memberId}")
    public UcenterMemberVO getMemberInfoById(@PathVariable String memberId) {
        UcenterMember member = ucenterMemberService.getById(memberId);
        UcenterMemberVO ucenterMemberVO = new UcenterMemberVO();
        BeanUtils.copyProperties(member, ucenterMemberVO);
        return ucenterMemberVO;
    }
}

